<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 产品
 * @author www.dingwei.cn
 */
class Product extends MY_Controller {
	
	const PRODUCT_DEUBG = FALSE;//参数调试输出log
	/**
	 * 商家模型
	 * @var MerchantUserModel
	 */
	public $mMerchant;
	
	/**
	 * 分类模型
	 * @var ConsumerCategoryModel
	 */
	public $mCategory;
	
	/**
	 * 评论模型
	 * @var MerchantCommentModel
	 */
	public $mComment;
	
	/**
	 * 产品模型
	 * @var ConsumerProductModel
	 */
	public $mProduct;
	
	/**
	 * 订单模型
	 * @var ConsumerOrderModel
	 */
	public $mOrder;
	
	/**
	 * 支付模型
	 * @var ConsumerPayModel
	 */
	public $mPay;
	
	/**
	 * 购物车模型
	 * @var ConsumerCartModel
	 */
	public $mCart;
	
	/**
	 * 活动模型
	 * @var ConsumerPromotionModel
	 */
	public $mPromotion;
	
	/**
	 * 活动模型
	 * @var MerchantPromotionModel
	 */
	public $mMerPromotion;
	
	/**
	 * 地址模型
	 * @var ConsumerAddressModel
	 */
	public $mAddress;
	
	/**
	 * 
	 * @var ConsumerMessageModel
	 */
	public $mMsg;
    /**
     *
     * @var MerchantMessageModel
     */
	public $mMerMsg;

    /**
     * @var DlnOrderModel
     */
	public $mDln;
	
	public $wxSDDefaultTime = [];//微信送达默认时间
	public function __construct(){
		parent::__construct();
		$this->loadModel('ConsumerCategoryModel', 'mCategory', 'consumer');
		$this->loadModel('MerchantCommentModel', 'mComment', 'merchant');
		$this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
		$this->loadModel('ConsumerCartModel', 'mCart', 'consumer');
        $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
	}

    /**
     * 店铺信息
     */
	public function merchant(){

        $merchantId = get('merchant_id');
        if (!$merchantId){
            show_404();
        }
        $tData = $this->getMerchantInfo($merchantId);

        $comment = $this->mComment->appGetCommentList($merchantId,0,1); // 评论列表
        $list = $this->getProductAll($merchantId); // 产品列表
        //预计送达时间
        $tBusiness = $this->mMerchant->getBusinessMerchant(array($merchantId));
        $expectArriveTime = '';
        if($tData['merchant']['business'] == 2 && !$tBusiness){
            $_time = $this->mMerchant->getBusinessTimeList($merchantId,true);

            $arriveTime = appArriveTime($_time,0,0,0,20);
            if($arriveTime['today']){
                $expectArriveTime = $arriveTime['today'][0].'起送';
            }elseif ($arriveTime['other']){
                $expectArriveTime = '明日'.$arriveTime['other'][0].'起送';
            }
        }

        $cart = $this->getMerchantCart($merchantId);

        $data = array(
            'merchantId' => $merchantId,
            'business_desc' => $expectArriveTime,
            'info' => $tData['merchant'],
            'cart' => $cart,
            'list' => $list,
            'comment' => $comment,
            'tData' => $tData,
            'submit' => true,
            'title' => $tData['merchant']['shop_name']
        );

        $this->view('product/merchant', $data, 'layer_mobile');
    }

    /**
     * 获取商家信息
     * @param $merchantId       int         商家id
     * @return array
     */
	public function getMerchantInfo($merchantId){
		$this->loadModel('MerchantPromotionModel', 'mMerPromotion', 'merchant');
		$this->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
		
		/**
		 * 商家信息
		 * @var array $tShop
		 */
        $tData = $this->mMerchant->getShopInfo($merchantId,true);

        if (! $tData){
            $this->appReturn(0,'商家不存在');
        }
        //周营业日
        $weekarray=array("","周一","周二","周三","周四","周五","周六","周日"); //定义一个数组
        $wk = '';
        if($tData['profile']['business_week']){

            $week = array_filter(explode(',',$tData['profile']['business_week']));
            foreach ($week as $k=>$v){
                $wk .= $weekarray[$v];
                if($k != count($week)){
                    $wk .= '、';
                }
            }
        }
        $tData['profile']['business_week'] = $wk;
        //营业时间
        $timeStr = '';
        foreach ($tData['profile']['business_time'] as $t){
            $timeStr .= $t['business_time_start'].'-'.$t['business_time_end'].' ';
        }
        $tData['profile']['business_time'] = $timeStr;

        $tData['bonus'] = (object)array();//商盟红包

        //分享信息
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $tShare = $this->mSetting->get('sharp_title,sharp_icon,sharp_url,sharp_desc');
        $tShare['sharp_icon'] = getImage($tShare['sharp_icon'],'og');
        $tData['share']['title'] = '赶快下载APP来领取';
        $tData['share']['url']  = $tShare['sharp_url'];
        $tData['share']['desc']  = $tShare['sharp_desc'].$tData['merchant']['shop_name']."的红包吧！";
        $tData['share']['icon']  = $tShare['sharp_icon'];
        // 是否收藏
        $tData['is_Collection'] = "1";//没有收藏
        if ($this->userId){
            if ($this->mUser->hasCollection($this->userId, $merchantId, 1)){
                $tData['is_Collection'] = "2";//有收藏
            }
        }
        $this->loadModel('MerchantPromotionModel','mMerPromotion','merchant');
        $promotion = array();
        //代金劵
        $tPromotion = $this->mMerPromotion->getCouponListByMerchantIds(array($merchantId));
        //代金劵
        if (isset($tPromotion[$merchantId])){
            $promotion[] = '下单即送代金劵';
        }
        //满减劵
        $tFullCut = $this->mMerPromotion->getFullCutListByMerchantIds(array($merchantId));
        $rule = '';
        //满减劵
        if (isset($tFullCut[$merchantId]['rule'])){
            $full = json_decode($tFullCut[$merchantId]['rule'],true);
            if ( ! $full){
                $full = array();
            }

            foreach ($full as $fk=>$fv){
                if ($fv['max_money']){
                    if ($rule){
                        $rule .= ',';
                    }

                    $rule .= '满'.$fv['max_money'].'减配送费'.$fv['money'];
                }
            }
        }
        if($rule){
            $promotion[] = $rule;
        }
        // 首单减免
        if ($tData['profile']['first_order_reduce'] > 0){
            $promotion[] = '首单减免'.$tData['profile']['first_order_reduce'].'元';
        }
        $tData['promotion'] = $promotion;

        return $tData;
	}

    /**
     * 获取产品列表
     * @param $merchantId       int     商家id
     * @return array
     */
    public function getProductAll($merchantId){
        $userId = 0;
        if ($this->userId) {
            $userId = $this->userId;
        }
        $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');

        //判断商家是否
        if ( ! $this->mMerchant->getInfo($merchantId)){
            $this->appReturn(0,'商家不存在');
        }
        $tData = array();

        //获取所有分类
        $tCustom = $this->mCategory->getCustomList($merchantId);
        //获取所有商品
        $tA = $this->mProduct->appGetAll($merchantId,$userId, true);

//        if(! $tA){
//            $this->appReturn(1,'该没有商品');
//        }

        $tProductIds = array();
        foreach ($tA as $k=>$v){
            if (!in_array($v['id'], $tProductIds)){
                $tProductIds[] = $v['id'];
            }
        }

        //获取产品属性
        $tProperty = $this->mProduct->getPropertyListByIds($tProductIds);

        //获取变体
        $tVariant = $this->mProduct->getPropertyVariantListByIds($tProductIds);
        //获取属性
        $tags = $this->mProduct->getTagsListByIds($tProductIds);

        foreach ($tA as $k=>$v){

            $v['property'] = isset($tProperty[$v['id']])?$tProperty[$v['id']]:array();
            $v['variant'] = isset($tVariant[$v['id']])?$tVariant[$v['id']]:array();
            $v['tags'] = isset($tags[$v['id']])?$tags[$v['id']]:array();

            $tData[$v['category_id']][] = $v;
        }

        foreach ($tCustom as $k=>$v){
            if (isset($tData[$v['id']])){
                //分类下没有商品，则删除
                $tCustom[$k]['product'] = $tData[$v['id']];
            }else{
                unset($tCustom[$k]);
            }
        }

        $tCustom = array_values($tCustom);

        return $tCustom;
    }

    /**
     * 商家购物车
     * @param $merchantId
     * @return array
     */
     public function getMerchantCart($merchantId){
        $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
        $this->loadModel('ConsumerCartModel', 'mCart','consumer');
        /**
         * 商家信息
         * @var array $tShop
         */

        $tData = $this->mMerchant->getShopInfo($merchantId,true);
        if (! $tData){
            $this->appReturn(0,'商家不存在');
        }

//        $tUser = array();
        $tData = array();
        $lunch_box_fee = 0; //打包费
        $total = 0; // 总金额
         $productAmount = 0;//商品总金额
         $number = 0; // 总数量
//        $sessionid = decode(post('sessionid'));
//        if ($sessionid){
//            $tUser = $this->mUser->getInfoBySessionid($sessionid);
//        }
        if ($this->userId){
            $tCart = $this->mCart->getList($this->userId,$merchantId);
            if (isset($tCart[$merchantId])){
                foreach ($tCart[$merchantId] as $k=>$v){
                    $v['property'] = array_values($v['property']);
                    $v['property_str'] = implode('/', $v['property']);
                    $lunch_box_fee += $v['lunch_box_fee'];
                    $productAmount += $v['price'] * $v['quantity'];
                    $number += $v['quantity'];
                    $tData[] = $v;
                }
            }
        }

        return array(
            'total' => sprintf('%.2f', $productAmount+$lunch_box_fee),
            'lunch_box_fee'=>$lunch_box_fee,
            'number' => $number,
            'list'=>$tData
        );
    }

	/**
	 * 获取产品列表[暂时未用]
	 */
	public function getProductList(){
		//表单验证
		$vConf = array(
				array('merchant_id', '商家id', 'required|is_natural_no_zero'),
				array('custom_id', '自定义分类id', 'required'),
				array('page', '分页', 'required|is_natural_no_zero'),
		);
		$this->formDataValidation($vConf);

		$merchantId = trim(post('merchant_id'));
		$customId = trim(post('custom_id'));
		$page = trim(post('page'));

		$this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');

		//判断商家是否
		if ( ! $this->mMerchant->getInfo($merchantId)){
			$this->appReturn(0,'商家不存在');
		}

		//分类是否
		if ( ! in_array($customId, array('recommend'))){
			if ( ! $this->mCategory->getCustomInfo($customId)){
				$this->appReturn(0,'分类不存在');
			}
		}

		$tA = $this->mProduct->appGetList($merchantId, $customId, $page);

		$this->appReturn(1,'',$tA);
	}

	/**
	 * 获取商家首页红包
	 */
	public function getCouponList(){
		//表单验证
		$vConf = array(
				array('merchant_id', '商家id', 'required|is_natural_no_zero'),
		);
		$this->formDataValidation($vConf);

		$tA = array(
				''
		);
	}

	/**
	 * 获取产品详情
	 */
	public function info(){
		$merchantId = trim(get('merchant_id'));
		$productId = trim(get('product_id'));
		//获取产品
		$tA = $this->mProduct->getInfo($productId,$merchantId);
		if ( ! $tA){
			show_error('产品不存在');
		}

		//获取产品详情
		$detail = $this->mProduct->getDetailList($productId);

		$this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
		$tAddress = $this->mAddress->getDefaultAddress($this->userId);
        if (empty((array)$tAddress)){
            $tA['shipping_fee'] = '0';
        }else{
            $tA['shipping_fee'] = (string)$this->shippingFreight(3,$tA['weight'], $tAddress['province'], $tAddress['city'], $tAddress['county']);
        }

		//获取评论列表
        $comment = $this->mComment->appGetCommentList($merchantId,$productId,1);

		//获取产品属性
		$tA['property'] = $this->mProduct->getPropertyList($productId);

		//获取变体
		$tA['variant'] = $this->mProduct->getPropertyVariantList($productId);
        $cart = $this->getMerchantCart($merchantId);
        $tData = $this->getMerchantInfo($merchantId);
        $data = array(
            'merchantId' => $merchantId,
            'info' => $tData['merchant'],
            'cart' => $cart,
            'comment' => $comment,
            'tA' => $tA,
            'detail' => $detail,
            'submit' => false,
            'title' => '商品详情'
        );
		$this->view('product/info', $data, 'layer_mobile');
	}

    /**
     * 全部评价
     */
    public function comment(){
        $merchantId = (int)get('merchant_id');
        $productId = (int)get('product_id');
        //获取产品
        $tA = $this->mProduct->getInfo($productId,$merchantId);
        if ( ! $tA){
            show_error('产品不存在');
        }
        //获取评论列表
        $list = $this->mComment->appGetCommentList($merchantId,$productId,1);
        $data = array(
            'productId' => $productId,
            'merchantId' => $merchantId,
            'list' => $list,
            'title' => '全部评价'
        );
        $this->view('product/comment', $data);
    }

    /**
     * 获取商家商品评论列表
     */
    public function getCommentList(){
        //表单验证
        $vConf = array(
            array('merchant_id', '商家id', 'required|is_natural_no_zero'),
            array('product_id', '商品id', 'required|is_natural_no_zero'),
            array('page', '分页', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);
        $merchantId = trim(post('merchant_id'));
        $page = trim(post('page'));
        $productId = (int)get('product_id');
        //验证商家是否存在
        if ( ! $this->mMerchant->getInfo($merchantId)){
            $this->appReturn(0,'商家不存在');
        }
        $page += 1;
        $tA = $this->mComment->appGetCommentList($merchantId,$productId,$page);
        $this->appReturn(1,'',$tA);
    }

	/**
	 * 更换规格
	 */
	public function getProperty(){
		if ($this->isDEBUG){
			$productId = 78;
			$sort = 1;
			$this->userId = 8;
		}else{

		//表单验证
 		$vConf = array(
				array('product_id', '产品id', 'required|is_natural_no_zero'),
				array('sort', '产品规格序号', 'required'),
		);

		$this->formDataValidation($vConf);

		$productId = post('product_id');
		$sort = post('sort');
		}


		//获取产品
		$tA = $this->mProduct->getInfo($productId);
		if ( ! $tA){
			$this->appReturn(0,'产品不存在');
		}

		//获取购物车信息
		$tCart = $this->mCart->getCartProductInfo($productId,$sort,$this->userId);
		if ( ! $tCart){
			$this->appReturn(0,'购物车商品不存在');
		}

		//获取已经选择的组合
		$tVariant = $this->mProduct->getPropertyVariantInfo($productId, $sort);
		if ( ! $tVariant){
			$this->appReturn(0,'该商品组合不存在');
		}
// 		p($tVariant);
		//获取产品属性
		$tData['property'] = $this->mProduct->getPropertyList($productId);

		//获取变体
		$tData['variant'] = $this->mProduct->getPropertyVariantList($productId);

		$html = $this->view('cart/specification',[
				'json'=>json_encode($tData),		//产品组合规格
				'product_id'=>$productId,			//产品id
				'sort'=>$sort,						//当前产品组合sort
				'varaint'=>$tVariant['property'],   //产品默认组合
				'quantity'=>isset($tCart['quantity'])?$tCart['quantity']:0,     //当前产品数量
		],'', '', '', true);

		if ($this->isDEBUG){
			echo $html;
			exit();
		}

		$data = array(
				'name'=>$tA['name'],
				'icon'=>$tA['icon']['og'],
				'quantity'=>isset($tVariant['quantity'])?$tVariant['quantity']:"0",
				'price'=>$tVariant['price'], //组合单价
				'html'=>$html,
		);
		$this->appReturn(1,'',$data);
	}

	/**
	 * 更换规格
	 */
	public function getProductProperty(){
//        $this->isDEBUG = true;
		if ($this->isDEBUG){
			$productId = 168;
		}else{
			//表单验证
			$vConf = array(
					array('product_id', '产品id', 'required|is_natural_no_zero'),
			);

			$this->formDataValidation($vConf);

			$productId = post('product_id');
		}

		//获取产品
		$tA = $this->mProduct->getInfo($productId);
		if ( ! $tA){
			$this->appReturn(0,'产品不存在');
		}

		//获取产品属性
		$tData['property'] = $this->mProduct->getPropertyList($productId);

		//获取变体
		$tData['variant'] = $this->mProduct->getPropertyVariantList($productId);

		//获取属性
        $tData['tags'] = $this->mProduct->getTagsList($productId);
// 		p($tData);
		$html = $this->view('cart/specification',[
				'json'=>json_encode($tData),		//产品组合规格
				'product_id'=>$productId,			//产品id
				'sort'=>'0',						//当前产品组合sort
				'varaint'=>json_encode(array()),   //产品默认组合
				'tags'=>json_encode(array()),   //产品默认组合
				'quantity'=>0,     //当前产品数量
		],'', '', '', true);

		if ($this->isDEBUG){
			echo $html;
			exit();
		}

		$data = array(
            'name' => $tA['name'],
            'icon' => $tA['icon']['og'],
            'quantity' => 0,
            'price' => $tA['goods_price'],
            'html' => $html,
		);
		$this->appReturn(1,'',$data);
	}

	/**
	 * 预览订单
	 */
	public function previewOrder(){

		//---------------------------------------------\
        //MY_Controller 中 将变量设置为 true 即可开启线下测试，
        //还有consumer 配置中，设置不过滤该链接
//        if ($this->isDEBUG){
//            $param = '[{"product_id":"78","sort":"2","quantity":"2"},{"product_id":"22","sort":"0","quantity":"1"}]';
////            $this->userId = 2;
//            $product = json_decode($param,true);
//        }else{
//        	//表单验证
//        	$vConf = array(
//        			array('product', '产品参数', 'required'),
//        	);
//        	$this->formDataValidation($vConf);
//
        	$product = post('product');
//        }
        //---------------------------------------------

        //加载模型
        $this->loadModel('MerchantUserModel', 'mMerchant','merchant');
        $this->loadModel('ConsumerProductModel', 'mProduct','consumer');
        $this->loadModel('MerchantPromotionModel', 'mMerPromotion','merchant');
        $this->loadModel('ConsumerOrderModel', 'mOrder','consumer');
        $this->loadModel('AdmSettingModel', 'mSett', 'admin');
        $this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
        //验证产品格式
        $tProduct = $this->mProduct->canAddOrder($this->userId, $product);
        $merchantId = (int)get('merchant_id');
        if ( ! is_array($tProduct)){
            $msg = (is_string($tProduct) ? $tProduct : '格式错误');
            if(!(strpos($msg,'下架') === false)){
                $exData = explode('-', $msg);
                show_error(substr($exData[1],0,-1).'已下架，请重新选购');
            }else{
                if ($merchantId > 0){
                    redirect(getUrl('product/merchant?merchant_id='.$merchantId));
                }else{

                    show_error('格式错误');
                }
            }
        }
        $isSpecial = false;
        $tMerchantIds = array();
        foreach ($tProduct as $k=>$v){
            if (!in_array($v['merchant_id'], $tMerchantIds)){
                $tMerchantIds[] = $v['merchant_id'];
            }
            if($v['is_special'] == 2){
                $isSpecial = true;
            }
        }
        if (! $tMerchantIds){
            show_error('商品商家不存在');
        }

        //获取商户信息
        $tMerchant = $this->mMerchant->getInfoByIds($tMerchantIds);
        if (! $tMerchant){
            show_error('商品商家不存在');
        }

        //批量获取商户满减劵
        $tFullCut = $this->mMerPromotion->getFullCutListByMerchantIds($tMerchantIds);

        /**
         * 获取首单减免
         */
        $tFirstOrder = $this->_firstOrder($tMerchantIds);

        /**---------------------------------------------
         * 多商品运费筛选
         * 备注：逻辑为，如果该商家的商品中，有一个为包邮，则不需要在寻找邮费。如果不是就赋值运费，运费的来源是商品的总质量+地区计算得来
         */
        $this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
        $tempLocation = $tMerchant[$tMerchantIds[0]];

        $tMaddress = [];
        $tMaddress = $this->mMerchant->getShopInfo($tMerchantIds[0]);
        $lat = $tMaddress['latitude'];
        $lng = $tMaddress['longitude'];

        $Address=[];
        $list = $this->mAddress->appGetList($this->userId, 1, true, $lat, $lng);
        foreach ($list as $l){
            if($l['over_distance']==1){
                $Address = $l;
                break;
            }
        }
        if ( ! is_array($Address)){
            $Address = (array)$Address;
        }
        $tmAmount = $this->_orderFee($tProduct, $product, empty($Address['id'])?0:$Address['id']);

        /**--------------------------
         * 获取商家地址[单个商家]
         */
        $tMaddress = [];
        $tMaddress = $this->mMerchant->getShopInfo($tMerchantIds[0]);
        $tMaddress['star_time'] = '';
        $tMaddress['end_time'] = '';
        $week_s = ['','周一','周二','周三','周四','周五','周六','周日'];
        $week_str = explode(',', $tMaddress['business_week']);
        foreach ($week_str as $k=>$v){
            if ($v){
                $tMaddress['week_str'][] = $week_s[$v];
            }
        }
        $tMaddress['week_str'] = implode(',', $tMaddress['week_str']);

        /**----------------------------------
         * 获取商家多段时间[单个商家]
         */
        $tTime = $this->mMerchant->getBusinessTimeList($tMerchantIds[0]);


        //预览订单
        $tOrder = array();
        $total = 0;//总金额
        $productAmount = 0;//商品总额
        foreach ($tProduct as $k=>$v){
            //如果没有规格
            if ( ! empty($v['property'])){
                $v['property'] = implode('/', json_decode($v['property'],true));
            }else{
                $v['property'] = '';
            }
            $v['icon'] = getImage($v['icon'],'og');

            //店铺名称
            $tOrder[$v['merchant_id']]['name'] = isset($tMerchant[$v['merchant_id']]['shop_name']) ? $tMerchant[$v['merchant_id']]['shop_name']:'';
            $tOrder[$v['merchant_id']]['is_bonus'] = $tMerchant[$v['merchant_id']]['able_use_coupon']; //是否支持红包
            $tOrder[$v['merchant_id']]['is_coupon'] = $tMerchant[$v['merchant_id']]['able_cash_coupon'];//是否支持代金劵
            $tOrder[$v['merchant_id']]['shop_type'] = $tMerchant[$v['merchant_id']]['shop_type'];//商家类型

            //邮费
            if ($tmAmount){
                $tOrder[$v['merchant_id']]['is_free_shipping'] = $tmAmount[$v['merchant_id']]['is_free_shipping'];
                $tOrder[$v['merchant_id']]['shipping_fee'] = $tmAmount[$v['merchant_id']]['shipping_fee'];
            }else{
                $tOrder[$v['merchant_id']]['is_free_shipping'] = 1;
                $tOrder[$v['merchant_id']]['shipping_fee'] = 0;
                $tmAmount[$v['merchant_id']]['shipping_fee'] = 0;
                $tmAmount[$v['merchant_id']]['is_free_shipping'] = 1;
            }
            $v['price'] = $v['variant_id']>0?$v['v_price']:$v['goods_price'];
            $v['goods_price'] = !empty($v['variant_id'])?$v['v_price']:$v['goods_price'];
            //商品
            $tOrder[$v['merchant_id']]['list'][] = $v;

            //计算总金额
            $total = $total + $v['goods_price']*$v['b_quantity'];
        }
//        p($tProduct);
        /**
         * 订单数据数组
         * @var array $tData
         */
        $tData = array();
        $shopType = 0;
        foreach ($tOrder as $k=>$v){
            $tempProduct = [];
            $amount = 0;
            $normalAmount = 0;//正价商品总价
            //打包费
            $lunch_box_fee = 0;
            foreach ($v['list'] as $kk=>$vProduct){
                $lunch_box_fee = $lunch_box_fee + $vProduct['lunch_box_fee'];
                $tempProduct[] = array(
                    'product_id'=>$vProduct['id'],
                    'sort'=>empty($vProduct['sort'])?'0':$vProduct['sort'],
                    'quantity'=>$vProduct['b_quantity'],
                    'price'=>$vProduct['price'],
                    'tags'=>$vProduct['tags'],
                );
                $amount += $vProduct['price']*$vProduct['b_quantity'];
                $productAmount += $vProduct['price']*$vProduct['b_quantity'];
//                if($vProduct['discount'] == 0){
//                    $normalAmount += $vProduct['price']*$vProduct['b_quantity'];
//                }
                $normalAmount += $vProduct['price']*$vProduct['b_quantity'];
            }

            //根据商家 与订单金额 获取满减额度
            $fullcut = array('money'=>0,'max_money'=>0);
            if ($tFullCut && $normalAmount){
                $fullcut = $this->mMerPromotion->getSatisfyFullCut($tFullCut[$k]['rule'], $normalAmount); //商品的总价
            }
            //首单减免
            $firstOrder = 0;
            if (isset($tFirstOrder[$k]) && ! empty($tFirstOrder[$k])&& $normalAmount){
                $firstOrder = $tFirstOrder[$k];
            }
            $_time = $this->mMerchant->getBusinessTimeList($k,true);

            $_for = getCustomConfig('expect_take_time');
            $_other = $this->mSett->get('rob_expect_time', 'deliveryman');
            $shopType = $v['shop_type'];
            //App需要的数据
            $tData[] = array(
                'merchant_id'=>$k,
                'product'=>$tempProduct,
                'coupon_id'=>"0",
                'amount'=>$amount,                      //该商家订单总金额
                'bonus_id'=>"0",
                'postal_card_id'=>"0",                  // 包邮卡
                'expense_type'=>"1",                    //默认0
                'shop_type'=>$v['shop_type'],
                'full_cut'=>$fullcut['money'],          //满减
                'first_order_reduce' => $firstOrder,
                'lunch_box_fee'=>$lunch_box_fee,        //合计打包费
                'expect_arrive_time'=>'',                    //送达时间
                'expect_arrive_time_s' => appArriveTime($_time, $_for, $_other, $tMerchant[$k]['expect_arrive_time'], 20),                    //送达时间

                'shortage_handing'=>['value'=>'','remark'=>''],                 //缺货处理
                'shortage_handing_s'=>$this->mOrder->getShortage(),//缺货处理的选项
// 					'shipping_fee'=>$tmAmount[$k]['shipping_fee'],
                'remark'=>'',
                'fee'=>$tmAmount[$k]['shipping_fee'],
            );
            //累加运费
            $total += $tmAmount[$k]['shipping_fee'] + $lunch_box_fee - $firstOrder - $fullcut['money'];

            //页面显示需要的数据
            $tOrder[$k]['lunch_box_fee'] = round($lunch_box_fee, 2);//打包费
            $tOrder[$k]['first_order_reduce'] = $firstOrder;//首单减免
            $tOrder[$k]['full_cut'] = $fullcut;//满减活动
            $tOrder[$k]['full_cut_str'] = '暂无活动';
            if ($fullcut['money']){
                $tOrder[$k]['full_cut_str'] = '满'.$fullcut['max_money'].'减配送费'.$fullcut['money'];
            }
        }
        //是否在店铺营业时间内
        $tBusiness = $this->mMerchant->getBusinessMerchant($tMerchantIds);
        $is_business = isset($tBusiness[$tMerchantIds[0]]) ? 2:1;
        //送达时间
        /**
         * 组织微信送达时间
         */
        $wxSD = appArriveTime($_time,$_for,$_other,$tMerchant[$k]['expect_arrive_time'],20,1,true);

        $selfWxSD = appArriveTime($_time,$_for,0,0,20, 1, true);

        $wxSDTime = $this->getWxSDTime($week_str,$wxSD);
        $selfLiftingTime = $this->getWxSDTime($week_str,$selfWxSD);
        $time = '';
        $selfTime = '';
        if(isset($wxSD['today']) && $wxSD['today']){
            $this->wxSDDefaultTime['time'] = isset($wxSD['today'][0]['value'])?$wxSD['today'][0]['value']:'';
        }else{
            $this->wxSDDefaultTime['time'] = isset($wxSD['other'][0]['value'])?$wxSD['other'][0]['value']:'';
        }

        foreach ($wxSDTime as $k=>$v){
            if (!$k && $wxSD['today']){
                //第一个是今天
                $time = $wxSD['today'][0]['label'];
                $wxSD['today'][0]['label'] = $is_business == 2?'立即送达':'';
                $wxSDTime[$k]['children'] = $wxSD['today'];
                $day_str= '今日';
                $day = date('d日', time());
            }elseif($wxSD['other']){
                $wxSDTime[$k]['children'] = $wxSD['other'];
                $day_str= '明日';
                $day = date('d日', strtotime('+1 day'));
            }

        }

        foreach ($selfLiftingTime as $k=>$v){
            if (!$k && $selfWxSD['today']){
                //第一个是今天
                $selfTime = $selfWxSD['today'][0]['label'];
                $selfWxSD['today'][0]['label'] = $is_business == 2?'立即自提':'';
                $selfLiftingTime[$k]['children'] = $selfWxSD['today'];
                $day_str= '今日';
                $day = date('d日', time());
            }elseif($selfWxSD['other']){
                $selfLiftingTime[$k]['children'] = $selfWxSD['other'];
                $day_str= '明日';
                $day = date('d日', strtotime('+1 day'));
            }
        }

        //设置默认送达时间
        if(isset($wxSD['today']) && $wxSD['today']){
            if($is_business == 2){
                $tData[0]['expect_arrive_time'] = '立即送达(预计'.$this->wxSDDefaultTime['time'].')';
            }else{
                $tData[0]['expect_arrive_time'] = '今日'.$this->wxSDDefaultTime['time'].'';
            }

        }else{

//            $tData[0]['expect_arrive_time'] = '立即送达(预计:'.$this->wxSDDefaultTime['date'].' '.$this->wxSDDefaultTime['time'].')';
            $tData[0]['expect_arrive_time'] = '明日'.$this->wxSDDefaultTime['time'];
        }

        /**
         * 代金券[单个商家]
         */
        $tCoupon = $normalAmount>0?$this->mPromotion->appGetCouponLogList($this->userId,1,1,false,$normalAmount,$tMerchantIds[0], true):array();
        /**
         * 红包【单个商家】
         */
        $tBonus = array();
        if($isSpecial == false && $normalAmount > 0){
            $tBonus = $this->mPromotion->appGetBonusLogList($this->userId,1,1,false,$normalAmount,true);
        }

        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $this->loadModel('ConsumerPostalCardModel', 'mPostalCard');
        if($total < 0){
            $total = 0;
        }
        $tPostalCard = $this->mPostalCard->appGetBonusLogList($this->userId,1,1,false,true,true);
       //处理送达时间：今天存在送达时间，隐藏明天的

        if($wxSDTime[0]){

            $time = $wxSDTime[0]['children'][0]['value'];
            unset($wxSDTime[1]);
        }else{

            $time = $wxSDTime[1]['children'][0]['value'];
            unset($wxSDTime[0]);
        }

        if($selfLiftingTime[0]){

            $selfTime = $selfLiftingTime[0]['children'][0]['value'];
            unset($selfLiftingTime[1]);
        }else{

            $selfTime = $selfLiftingTime[1]['children'][0]['value'];
            unset($selfLiftingTime[0]);
        }

		$data = array(
		    'isSpecial' => $isSpecial,
		    'distribution' => $this->mSetting->getExplain('distribution_fee_desc'),
            'order'=>$tOrder,
            'total'=>sprintf('%.2f',$total),
            'totalAmount'=>sprintf('%.2f',$productAmount + $lunch_box_fee),       //商品总额+餐费费
	        'shopType'=>$shopType,
            'title' => '预览订单',
		    'data'=>$tData,
		    '_for'=>$_for,//送达时间
		    'address'=>$Address,
		    'mAddress'=>$tMaddress,
		    'fee'=>array_values($tmAmount),
		    '_time'=>$tTime,
		    'firstOrder'=>$firstOrder,
		    'coupon'=>$tCoupon,
		    'bonus'=>$tBonus,
		    'postalCard'=>$tPostalCard, // 包邮卡
		    'fullcut'=>$fullcut['money'],
		    'wxSDTime'=>json_encode($wxSDTime),
		    'selfLiftingTime'=>json_encode($selfLiftingTime),
		    'wxDefaultTime'=>$this->wxSDDefaultTime,
            'day' => $day,
            'day_str' => $day_str,
            'time' => $time,
            'selfTime' => $selfTime,
            'productJson' => json_encode($product),
            'lat' =>$lat,
            'lng' =>$lng,
		);

		$this->view('product/preview', $data, 'layer_mobile');
	}

	public function test(){
        $this->loadModel('AdmSettingModel', 'mSett', 'admin');
        $tMaddress = [];
        $tMaddress = $this->mMerchant->getShopInfo(33);

        $week_str = explode(',', $tMaddress['business_week']);

        $_time = $this->mMerchant->getBusinessTimeList(33,true);

        $_for = getCustomConfig('expect_take_time');
        $_other = $this->mSett->get('rob_expect_time', 'deliveryman');
        /**
         * 组织微信送达时间
         */

        $wxSD = appArriveTime($_time,$_for,$_other,20,1,true);

        $wxSDTime = $this->getWxSDTime($week_str,$wxSD);
        foreach ($wxSDTime as $k=>$v){
            if (!$k && $wxSD['today']){
                //第一个是今天
                $wxSDTime[$k]['children'] = $wxSD['today'];
                $this->wxSDDefaultTime['time'] = '立即送达';
//                $this->wxSDDefaultTime['time'] = $wxSD['today'][0]['value'];
            }else{
                $wxSDTime[$k]['children'] = $wxSD['other'];
                $this->wxSDDefaultTime['time'] = $wxSD['other'][0]['value'];
            }
        }

        //设置默认送达时间
        $tData[0]['expect_arrive_time'] = $this->wxSDDefaultTime['date'].' '.$this->wxSDDefaultTime['time'];

    }
	/**
	 * 获取微信送达时间
	 * @param unknown $week_str
	 * @return array|string[]
	 */
	private function getWxSDTime($week_str,$wxSD){
	    $wxSDTime = [];
	    $_day = 0;
	    $num = 0;
	    while ($num < 2){
	        //循环7次
            if(!$wxSD['today'] && $_day == 0){
                $_day = 1;
            }
	        $now = strtotime('+'.$_day.' day',time());//当前时间
	        $now_d = date('d',$now);
	        $now_w = date('w',$now);

	        if ($now_w == 0){
	            $now_w = 7;//星期日 转换
	        }

	        if (in_array($now_w, $week_str)){
                if(isset($wxSD['today']) && $wxSD['today'] && $num == 0){
                    $wxSDTime[] =['label'=>'今日','value'=>$now_d.'日'];//满足的
                }else{
                    $wxSDTime[] =['label'=>'明日','value'=>$now_d.'日'];//满足的
                }

	            if ( !isset($this->wxSDDefaultTime['date'])){
	                //第一天的日期
	                $this->wxSDDefaultTime = ['date'=>$now_d.'日'];
	            }
	            $num++;
	        }
	        $_day++;
	    }

	    return $wxSDTime;
	}
	/**
	 * 商品下单[商盟]
	 */
	public function orderSm(){
		//表单验证
		$vConf = array(
				array('param', '其他参数参数', 'required'),
		);
		$this->formDataValidation($vConf);

		$param = json_decode(post('param'),true);
		$address_id = post('address_id');//地址id


// 		$param = json_decode('[{"amount":128.5,"bonus_id":"7","coupon_id":"2","expense_type":2,"fee":0.0,"merchant_id":"3","product":[{"price":"128.50","product_id":"43","quantity":"1","sort":"0"}],"red":0.0,"remark":"","ticket":0.0},{"amount":61.5,"bonus_id":"8","coupon_id":"5","expense_type":2,"fee":0.0,"merchant_id":"13","product":[{"price":"20.50","product_id":"72","quantity":"3","sort":"1"}],"red":0.0,"remark":"","ticket":0.0}]',true);
// 		$address_id = 19;
		if ( ! $param){
			$this->appReturn(0,'提交的参数格式错误');
		}

		/**
		 * 加载模型
		 */
		$this->loadModel('MerchantUserModel', 'mMerchant','merchant');
		$this->loadModel('ConsumerProductModel', 'mProduct','consumer');
		$this->loadModel('ConsumerOrderModel', 'mOrder','consumer');
		$this->loadModel('ConsumerPayModel', 'mPay','consumer');
		$this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
		$this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
		$this->loadModel('MerchantPromotionModel', 'mMerPromotion','merchant');
		$this->loadModel('ConsumerPostalCardModel', 'mPostalCard','consumer');

		/**--------------------------------------------------------------
		 * 验证产品格式
		 */
		$products 	= array();//产品参数数组
		$tParam 	= array();//以商家为标识的数组
		$bBonusIds 	= array();//批量红包id
		$bCouponIds = array();//批量代金劵id
        $postalCardIds = array(); // 包邮卡
		foreach ($param as $k=>$v){

			if ( ! $v['expense_type']){
				$this->appReturn(0,'请选择消费模式');
			}

			if ($v['expense_type'] == 1){
			    if (! $address_id){
			        $this->appReturn(0,'必须选择送货地址');
			    }
			}

			//获取红包id
			if ($v['bonus_id'] && in_array($v['bonus_id'], $bBonusIds)){
				$this->appReturn(0,'一个红包只能使用一个商铺');
			}
			$bBonusIds[] = $v['bonus_id'];
			if ($v['expense_type'] == 1) {
                $postalCardIds[] = $v['postal_card_id']; // 包邮卡
            }
			//获取代金劵id
			if ($v['coupon_id'] && in_array($v['coupon_id'], $bCouponIds)){
				$this->appReturn(0,'一个代金劵只能使用一个商铺');
			}
			$bCouponIds[] = $v['coupon_id'];

			//将提交的产品参数合并[为了验证产品正确性]
			$products = array_merge($products, $v['product']);//合并产品参数

			//以商家为标识组合[方便后面验证 实时数据 与 app提交的数据对比验证]
			unset($v['expect_arrive_time_s']);
			$tParam[$v['merchant_id']] = $v;
		}

		/**----------------------------------------------------------------
		 * 验证产品参数
		 * 备注：获取数据库中，按商品 以及商品规格的正确性
		 * @var Ambiguous $tProduct
		 */
		$tProduct = $this->mProduct->canAddOrder($this->userId, $products);
		if ( ! is_array($tProduct)){
			$this->appReturn(0,(is_string($tProduct) ? $tProduct : '格式错误'));
		}

		/**-------------------------------------------------------------
		 * 批量获取红包
		 */
		$tBonus = $this->mPromotion->getBonusByIds($bBonusIds,$this->userId);
		$tCoupon = $this->mPromotion->getCouponByIds($bCouponIds,$this->userId);
        $tPostalCard = array();
		if(!empty($postalCardIds)) {
            $tPostalCard = $this->mPostalCard->getInfoIds($postalCardIds, $this->userId);
        }
		/**----------------------------------------------------------------
		 * 获取收货地址
		 */
		$tAddress = $this->mAddress->getInfo($address_id,$this->userId);

		/**--------------------------------------------
		 * 批量获取商户信息
		 */
		$tMerchantIds = array();
		foreach ($tProduct as $k=>$v){
			if (!in_array($v['merchant_id'], $tMerchantIds)){
				$tMerchantIds[] = $v['merchant_id'];
			}
		}

		if (! $tMerchantIds){
			$this->appReturn(0,'商品商家不存在');
		}

		$tMerchant = $this->mMerchant->getInfoByIds($tMerchantIds);
		if (! $tMerchant){
			$this->appReturn(0,'商家不存在');
		}

		/**
		 * 批量获取商家的满减劵规则
		 */
		$tFullCut = $this->mMerPromotion->getFullCutListByMerchantIds($tMerchantIds);

		/**
		 * 获取首单减免
		 */
		$tFirstOrder = $this->_firstOrder($tMerchantIds);

		/**---------------------------------------------
		 * 多商品运费筛选
		 * 备注：逻辑为，如果该商家的商品中，有一个为包邮，则不需要在寻找邮费。如果不是就赋值运费，运费的来源是商品的总质量+地区计算得来
		 */
		$tmAmount = $this->_orderFee($tProduct, $products, $address_id, $done = true);

		/**---------------------------------------------------------------------------------
		 * 订单按商家分组
		 * @var array $tOrder
		 */
		$tOrder = array();
		$sale_quantity = [];//产品总库存集合 记录产品销量

		foreach ($tProduct as $k=>$v){

		    //累加当前产品打包费
            if ( ! isset($tOrder[$v['merchant_id']]['lunch_box_fee'])){
                $tOrder[$v['merchant_id']]['lunch_box_fee'] = 0;
            }

            $tOrder[$v['merchant_id']]['lunch_box_fee'] += $v['lunch_box_fee'];

            //获取价格
            $v['v_price'] = $v['variant_id']?$v['v_price']:$v['goods_price'];

			//初始化商品金额
			if ( ! isset($tOrder[$v['merchant_id']]['product_amount'])){
				$tOrder[$v['merchant_id']]['product_amount'] = 0;
			}
			//邮费模式
			$tOrder[$v['merchant_id']]['is_free_shipping'] = isset($tmAmount[$v['merchant_id']]['is_free_shipping'])?$tmAmount[$v['merchant_id']]['is_free_shipping']:1;
			//商品总金额
			$tOrder[$v['merchant_id']]['product_amount'] += $v['v_price'] * $v['b_quantity'];
			//商品
			$tOrder[$v['merchant_id']]['list'][] = $v;

			$sale_quantity[$v['id']] = empty($v['sale_quantity']) ? "0" : $v['sale_quantity'];//产品当前销量
		}

//p($tOrder);
		/**-----------------------------------------------------------------------------------
		 * 订单数据 保存订单
		 */
		$tData 		= array();//订单
		$tempCode 	= array();//订单号
		$payCode 	= getOrderCode();//预支付订单号
		$total 		= 0;//总金额
		//p($tMerchant);
		foreach ($tOrder as $k=>$v){
			$code = getOrderCode();
			$tempCode[] = $code;//存入订单号

			//非包邮
			$total_amount = $v['product_amount'];
            if($tMerchant[$k]['min_consume'] > $total_amount){
                $this->ajaxReturn(0, '不满足商家起送价');
            }
			$shipping_fee = 0;
			if ($v['is_free_shipping'] == 1 && ($tParam[$k]['expense_type'] == 1) ){
				if ($tmAmount[$k]['shipping_fee'] != $tParam[$k]['fee']){
//				    p($tmAmount[$k]['shipping_fee'].'-'.$tParam[$k]['fee']);
					$this->appReturn(0,'邮费好像有变动,请重新下单');
				}

				//送货上门、非包邮  加上邮费
				$total_amount = $v['product_amount'] + $tmAmount[$k]['shipping_fee']; //[商品金额 + 运费]
				$shipping_fee = $tmAmount[$k]['shipping_fee']; //当前运费[订单实际]
			}

            //验证打包费
            if ($tParam[$k]['lunch_box_fee'] != $v['lunch_box_fee']){
                $this->appReturn(0,'打包费好像有变动,请重新下单');
            }
            $total_amount = $total_amount + $tParam[$k]['lunch_box_fee'];//加上打包费

			//实际支付金额
			$reality_amount = $total_amount;//[总金额 - 优惠]

			//代金劵
			$coupon = 0;
			if (isset($tCoupon[$tParam[$k]['coupon_id']])){
				$coupon = $tCoupon[$tParam[$k]['coupon_id']]['money'];
				if ($total_amount <= $coupon){
					$this->appReturn(0,'总消费太少了，结果让代金劵都抵完了');
				}
				$reality_amount = $reality_amount - $coupon;
			}

			//红包
			$bonus = 0;
			if (isset($tBonus[$tParam[$k]['bonus_id']])){
				$bonus = $tBonus[$tParam[$k]['bonus_id']]['money'];
				if ($total_amount <= $bonus){
					//$this->appReturn(0,'总消费太少了，结果让红包都抵完了');
				}
				$reality_amount = $reality_amount - $bonus;
			}

			//包邮卡
            $postalCard = 0;
			if (isset($tPostalCard[$tParam[$k]['postal_card_id']])){
				$postalCard = $tPostalCard[$tParam[$k]['postal_card_id']]['money'];
				$sf = $shipping_fee - $postalCard;
                $sf = $sf < 0 ? $shipping_fee : $postalCard;
                $reality_amount = $reality_amount - $sf;
                $postalCard = $sf;
			}

			//根据商家 与订单金额 获取满减额度
			$fullcut = array('money'=>0,'max_money'=>0);

			if ($tFullCut){
				$fullcut = $this->mMerPromotion->getSatisfyFullCut($tFullCut[$k]['rule'], $v['product_amount']);//商品总价
				if ($fullcut['money'] != $tParam[$k]['full_cut']){
					$this->appReturn(0,'满减金额好像有变动,请重新下单');
				}
				$reality_amount = $reality_amount - $fullcut['money'];//实际支付金额 减去满减劵
			}

			//首单减免
			$firstOrder = 0;
			if (isset($tFirstOrder[$k]) && ! empty($tFirstOrder[$k])){
				$reality_amount = $reality_amount - $tFirstOrder[$k];//实际支付金额 减去满减劵
				$firstOrder = $tFirstOrder[$k];
			}

			//地址
			$address = '';
			$contacts = '';
			$gender = '';
			$mobile = '';
			$province_id = 0;
			$city_id = 0;
			$county_id = 0;
			$latitude = '';
			$longitude = '';
			if ($tAddress){
				$address = $tAddress['address_desc'];
				$contacts = $tAddress['consignee'];
				$gender = $tAddress['gender'];
				$mobile = $tAddress['mobile'];
				$province_id = $tAddress['province'];
				$city_id = $tAddress['city'];
				$county_id = $tAddress['county'];
                $latitude = $tAddress['latitude'];
                $longitude = $tAddress['longitude'];
			}

			//设置到订单数据【后面组合订单产品 计算优惠后的实际占比金额】
			$tOrder[$k]['coupon_amout'] = $coupon;
			$tOrder[$k]['bonus_amout'] = $bonus;
			$tOrder[$k]['reality_amount'] = $reality_amount; //用户实际付款

            if ($reality_amount < 0){
                $reality_amount = 0;
            }
            $web_percent =isset($tMerchant[$k]['percent'])?$tMerchant[$k]['percent']:'0';
            $webservice = round($v['product_amount']*$web_percent/100, 2); //平台服务费
            $min_order_web_amount = isset($tMerchant[$k]['min_order_web_amount'])?$tMerchant[$k]['min_order_web_amount']:'0';//保底抽成
            if($webservice < $min_order_web_amount){
                $webservice = $min_order_web_amount;
            }
            $merchantIncome = $reality_amount - $shipping_fee - $webservice + $bonus;//商家收入
            if($merchantIncome <= 0){
                $webIncome = $reality_amount - $shipping_fee;
            }else{
                $webIncome = $webservice - $bonus; //平台收入
            }

            $deliverymanIncome = $shipping_fee;//配送员收入


            $arrivetime = date('Y-m-').str_replace('日', '', $tParam[$k]['expect_arrive_time'].':00');
            $BeginDate=date('Y-m-01', strtotime(date("Y-m-d")));
            if(strtotime("$BeginDate +1 month -1 day") == strtotime(date('Y-m-d')) && date('d',strtotime($arrivetime)) != date('d')){
                //月末的预订单
                $arrivetime = dateFormat(strtotime("$arrivetime +1 month"), true);
            }
            //订单状态
            $status = 1;
            if($reality_amount == 0){
                $status = $tParam[$k]['expense_type'] == 1? 2:3;

            }
			$tData[] = array(
					'merchant_id'=>$k,
					'consumer_id'=>$this->userId,
					'code'=>$code,
					'pay_code'=>$payCode,
					'type'=>isset($tMerchant[$k]['category_id'])?$tMerchant[$k]['category_id']:'0',//类型
					'expense_type'=>$tParam[$k]['expense_type'],//商家消费类型
					'pay_type'=>$reality_amount>0 ? 0:1,
					'pay_time'=>$reality_amount>0 ? '':time(),
					'product_amount'=>$v['product_amount'],//0.01,//商品的价格
					'total_amount'=>$total_amount,//0.01,
					'reality_amount'=>$reality_amount,//0.01,//下单前实际支付金额
			        'remark'=>$tParam[$k]['remark'],
					'status'=>$status,//待支付
					'contacts'=>$contacts,
					'gender'=>$gender,
					'mobile'=>$mobile,
					'address'=>$address,
					'latitude'=>$latitude,
					'longitude'=>$longitude,
					'province_id'=>$province_id,
					'city_id'=>$city_id,
					'county_id'=>$county_id,
					'shipping_fee'=>$shipping_fee,
					'percent'=>$web_percent,//类型
                    'bonus'=>$bonus,
                    'postal_card'=>$postalCard > $shipping_fee ?$shipping_fee:$postalCard,
                'lunch_box_fee'=>$tParam[$k]['lunch_box_fee'],
                    'merchant_discount'=> sprintf("%.2f", $fullcut['money'] + $firstOrder + $coupon),
					'param'=>json_encode(array(
							'coupon'=>$coupon,
							'bonus'=>$bonus,
							'postal_card'=>$postalCard,
							'full_cut'=>$fullcut['money'],
							'first_order_reduce'=>$firstOrder,
                            'lunch_box_fee'=>$tParam[$k]['lunch_box_fee'],
						)),
					'addtime'=>time(),

                    //新增字段
                    'deliveryman_income' => $deliverymanIncome,
                    'merchant_income' => $merchantIncome,
                    'web_income' => $webIncome,
                    'after_sale'=>1,//未申请
                    'is_comment'=>1,//未评价
                    'shipping_type'=>$tMerchant[$k]['shipping_type'],//配送模式 根据该商家来设置的
                    'shortage_handing'=>json_encode($tParam[$k]['shortage_handing']),//{"value":"s1","remark":"备注信息"}
			    'expect_arrive_time'=>strtotime($arrivetime),//送达时间
			);
			//计算总金额
			$total = $total + $reality_amount;
		}


		$this->db->trans_begin();//开启事务

		if ( ! $tId = $this->mOrder->saveBatch($tData)){
			$this->db->trans_rollback();
			$this->appReturn(0,'下单失败');
		}

		/**--------------------------------------------------------------
		 * 组合 订单产品信息
		 */
		//获取订单id
		$tempOrder = $this->mOrder->getOrderByCodes($tempCode);
		if ( ! $tempOrder){
			$this->db->trans_rollback();
			$this->appReturn(0,'下单失败');
		}


		//组合订单产品信息
		foreach ($tOrder as $k=>$v){
			foreach ($v['list'] as $kk=>$vv){
                $price = empty($vv['variant_id'])?$vv['goods_price']:$vv['v_price'];
				$orderProduct[] = array(
						'order_id'=>$tempOrder[$k],//根据商户id 获取订单id
						'product_id'=>$vv['id'], //产品id
						'price'=>$price,
						'quantity'=>$vv['b_quantity'],
						'reality_amount'=> sprintf('%.2f',$price*$vv['b_quantity']),
						'variant_id'=>empty($vv['variant_id'])?"0":$vv['variant_id'],//变体序号
						'tags'=>empty($vv['tags'])?"":$vv['tags'],//属性
				);

				/**
				 * 处理商品变体
				 */
				$sale_quantity[$vv['id']] = (isset($sale_quantity[$vv['id']]) ? $sale_quantity[$vv['id']] : 0 )+ 1;
				if ( ! $this->mProduct->savePropertyVariant(array('sale_quantity'=>$vv['sale_quantity'] + 1),$vv['id'],$vv['variant_id'])){
					$this->db->trans_rollback();
					$this->appReturn(0,'下单失败');
				}
				#end
			}
		}

		//判断商品数量是否一致
		if (count($products) != count($orderProduct)){
			$this->db->trans_rollback();
			$this->appReturn(0,'下单失败');
		}

		//批量保存订单产品信息
		if ( ! $this->mOrder->saveOrderProduct($orderProduct)){
			$this->db->trans_rollback();
			$this->appReturn(0,'下单失败');
		}


		/**
		 * 下单成功后，处理红包，处理代金劵 处理购物车
		 */
		$this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
		if ( ! $this->mPromotion->saveBatchBonusLog(array('status'=>2),$bBonusIds)){
			$this->db->trans_rollback();
			$this->appReturn(0,'下单失败');
		}

		if ( ! $this->mPromotion->saveBatchCouponLog(array('status'=>2),$bCouponIds)){
			$this->db->trans_rollback();
			$this->appReturn(0,'下单失败');
		}

		// 处理包邮卡
		if (!empty($postalCardIds) && !empty($tPostalCard)){
		    $this->db->where_in('id', $postalCardIds);
            $query = $this->mPostalCard->update($this->mPostalCard->tbPostalCardLog,
                array(
                    'status'=>2,
                    'order_id' => $tempOrder[$tMerchantIds[0]],
                    'usedtime' => time()
                )
            );
            if ( !$query){
                $this->db->trans_rollback();
                $this->appReturn(0,'下单失败');
            }
        }

		/**
		 * 删除购物车
		 */
		foreach ($products as $k=>$v){

			//循环删除该消费者 购物车中的该商品
			$this->db->where(array(
					'consumer_id'=>$this->userId,
					'product_id'=>$v['product_id'],
					'variant_id'=>$v['sort'],
			));

			if ( ! $this->mCart->delete($this->mCart->tbShoppingCart)){
				$this->db->trans_rollback();
				$this->appReturn(0,'下单失败');
			}
		}

		//订单下单时 减少库存
		$this->loadModel('AdmSettingModel', 'mSet','admin');
		$reduce_stock = $this->mSet->get('reduce_stock');

		if ($reduce_stock == 1){
			//下单时减少
			foreach ($tOrder as $k=>$v){
				$result = $this->mOrder->reduceStocks($tempOrder[$k]);
				if($result['status'] == 0){
                    $this->db->trans_rollback();
                    $this->appReturn(0, $result['message']);
                }
			}
		}

		/**
		 * 增加销量
		 */
//		foreach ($sale_quantity as $productId => $quantity){
//			if ( ! $this->mProduct->save(array('sale_quantity'=>$quantity),$productId)){
//				$this->db->trans_rollback();
//				$this->appReturn(0,'下单失败[ERROR:1001]');
//			}
//		}

		/**
		 * 获取支付参数
		 */
		$tData = array(
		      'code'=>$tempCode[0],//预支付订单
				'total_amount'=>$total,
		);

		$this->db->trans_commit();
		$this->appReturn(1,'订单提交成功',$tData);
	}

    /**
     * 立即支付
     */
    public function orderPay(){
        $code = get('code');
        if(!$code){
            show_error('订单号必须');
        }
        //如果解析成功
        $arrayCode = json_decode($code,true);

        //加载模型
        $this->loadModel('ConsumerOrderModel', 'mOrder','consumer');
        $this->loadModel('ConsumerPayModel', 'mPay', 'consumer');

        $amount = 0;
        $tempCode = array();
        if (is_array($arrayCode)){
            $tOrders = $this->mOrder->getInfoByCodes($arrayCode);
            if ( ! $tOrders){
                show_error(0,'订单不存在');
            }

            foreach ($tOrders as $k=>$v){
                if ($v['status'] != 1){
                    //待支付
                    show_error('订单已经被取消');
                }
                $tempCode[] = $v['code'];
                $amount += $v['reality_amount'];
            }
        }else{

            $tOrder = $this->mOrder->getInfoByCode($code, 0,$this->userId);
            if ( ! $tOrder){
                $this->appReturn(0,'订单不存在');
            }
            if ($tOrder['status'] == 2){
                //已支付
                redirect(getUrl('order/orderDetail?order_id='.$tOrder['id']));
            }
            if ($tOrder['status'] != 1){
                //待支付
                show_error('订单已经被取消');
            }

            $tempCode[] = $tOrder['code'];
            $amount = $tOrder['reality_amount'];
        }

        /**
         * 创建预支付订单
         */
        $this->db->trans_begin();//事务

        $payCode = getOrderCode();
        $data = array(
            'consumer_id'=>$this->userId,
            'code'=>$payCode,
            'amount'=>$amount,
            'type'=>2,//充值
            'pay_type'=>0, //没有支付方式
            'status'=>1,//未支付
            'param'=>json_encode($tempCode),
            'addtime'=>time(),
        );

        if ( ! $this->mPay->savePayOrder($data)){
            $this->db->trans_rollback();
            show_error('调起支付失败[ERROR:01]');//预支付订单失败
        }

        /**
         * 更新订单预支付订单号
         */
        if ( ! $this->mOrder->saveBatch(array('pay_code'=>$payCode),0,$tempCode)){
            $this->db->trans_rollback();
            show_error('调起支付失败[ERROR:02]');
        }
//        $amount = 0.01;
        /**
         * 获取支付参数
         */
        $tA['balance'] = $this->userBalance;
        $tA['code'] = $payCode;
        $tA['amount'] = $amount;
        $tA['url'] = getUrl('order/orderDetail?order_id='.$tOrder['id']);
        //获取支付宝
//        $tA['alipay'] = $this->mPay->_getAliPay($payCode,$amount);
        //获取微信支付
        $jsApiParameters = $this->mPay->_getWeChatPay($payCode,$amount);
        if(isset($jsApiParameters['return_code']) && $jsApiParameters['return_code'] == 'FAIL'){
            show_error($jsApiParameters['return_msg']);
        }
        $this->db->trans_commit();
        $tData = array(
            'title' => '立即支付',
            'info' => $tA,
            'jsApiParameters' => $jsApiParameters,
        );
        $this->view('product/orderPay', $tData, 'wx_validation,toastmessage,layer_mobile');
    }


    public function paySuccess(){
        $tData = array(
            'title' => '立即支付',
        );
        $this->view('product/success',$tData);
    }

    /**
     * 验证收货地址以及经纬度
     * @param string $sendAddress      起始配送地址
     * @param string $latitude         起始纬度
     * @param string $longitude        起始经度
     * @param string $sendToDddress    配送到达地址
     * @param string $sendToLatitude   配送到达纬度
     * @param string $sendToLongitude 配送到达经度
     * @param int $fee  所花费运费
     * @return array
     */
    /*
	private function checkCoordinates($sendAddress,$latitude,$longitude,$sendToDddress,$sendToLatitude,$sendToLongitude,$fee){

        get_instance()->loadModel('AdmSettingModel', 'mSett', 'admin');
        $config = $this->mSett->get('map_key as ak,base_distribution_fee,base_distribution_distance,base_distribution_weight
				,exceed_base_distance,exceed_base_weight,rob_expect_time,exceed_base_distance_number,exceed_base_weight_number', 'deliveryman');
        $url = 'http://api.map.baidu.com/geocoder/v2/?address='.$sendAddress.'&output=json&ak='.$config['ak'];

        $tA = $this->_request($url);

        if($tA == false){
            return ['status' => 0, 'message' => '地址解析错误'];
        }

        $tS = dsitance($latitude, $longitude, $tA[0], $tA[1]);
        if( ! is_numeric($tS) || $tS > 100){
            return ['status' => 0, 'message' => '店铺地址有误差'];
        }

        $url = 'http://api.map.baidu.com/geocoder/v2/?address='.$sendToDddress.'&output=json&ak='.$config['ak'];
        $tA = $this->_request($url);

        if($tA == false){
            return ['status' => 0, 'message' => '地址解析错误'];
        }

		$tS = dsitance($sendToLatitude, $sendToLongitude, $tA[0], $tA[1]);

		if( ! is_numeric($tS) || $tS > 100){
			return ['status' => 0, 'message' => '送货地址有误差'];
		}

		$distance = dsitance($latitude, $longitude, $sendToLatitude, $sendToLongitude);

		$tIncome = $this->getIncome($distance / 1000, 0, $config);

		if($tIncome != $fee){
			return ['status' => 0, 'message' => '配送费发生了变化，请重新下单'];
		}
		return ['status' => 1, 'message' => ''];
    }*/


	/**
	 * 获取店铺首单减免金额
	 * @param unknown $merchantIds 商家ids数组
	 * @return array 商家为键的数组 ["1"=>10]
	 */
	private function _firstOrder($merchantIds){
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        //获取店铺订单数量
        $tA = $this->mOrder->firstOrderByMerchantId($merchantIds, $this->userId);

        $data = array();
        foreach ($tA as $v){
            if($v['count'] == 0 && $v['first_order_reduce'] > 0){
                $data[$v['merchant_id']] = $v['first_order_reduce'];
            }
        }

        return $data;
	}

	/**
	 * 从实际订单产品中，获取商家的运费
	 * @param unknown $tProduct
	 * @param unknown $products
	 * @param unknown $address_id
	 * @return array|number|unknown
	 * @author zyl
	 */
	private function _orderFee($tProduct, $products, $address_id, $done = false){

		/**
		 * 根据当前地址获取邮费
		 */
		$tShipping = array();
		if ($address_id){
			$tShipping = $this->shippingFee($products,$address_id, $done);
		}
		//由于没有包邮不包邮的模式
        return $tShipping;
		/**---------------------------------------------
		 * 多商品运费筛选
		 * 备注：逻辑为，如果该商家的商品中，有一个为包邮，则不需要在寻找邮费。如果不是就赋值运费，运费的来源是商品的总质量+地区计算得来
		 */

		$tmAmount = array();

        foreach ($tShipping as $kk=>$vv){
            //寻找运费
            $tmAmount[$vv['merchant_id']] = $vv;//设置配送费
        }

        foreach ($tProduct as $k=>$v){
			//判断之前
            if ($v['is_free_shipping'] == 2){
                //包邮
                $tmAmount[$v['merchant_id']]['shipping_fee'] = 0;//配送费0
            }
		}

		return $tmAmount;
	}

    /**
     * 配送费计算
     * @param int $shipping_id  配送方式id
     * @param $weight    重量
     * @param $province   省
     * @param $city      市
     * @param $county    区县
     * @return int
     */
	private  function shippingFreight($shipping_id = 3,$weight,$province,$city,$county){
        $this->loadModel('AdmShippingModel', 'mShipping','admin');

        if($weight == 0) return 0; // 商品没有重量
        if($shipping_id == '') return 0;

        //查找配送区域
        $config = '';

        $tA = $this->mShipping->getAllShippingArea($shipping_id);
        foreach ($tA as $k=>$v){
            $regionId = json_decode($v['region_config'], true);
            if($config == '' &&  in_array($county,$regionId)){
                $config = $v['config'];
            }

            if($config == '' && in_array($city,$regionId)){
                $config = $v['config'];
            }

            if($config == '' && in_array($province,$regionId)){
                $config = $v['config'];
            }
        }

        if(!$config){
            return 0;
        }

        $config = json_decode($config, true);

        // 1000 克以内的 只算个首重费
        if($weight < 1000)
        {
            return $config['money'];
        }
        // 超过 1000 克的计算方法
        $weight = $weight - 1000; // 续重

        $freight = $config['money'] +  $weight * $config['add_money']; // 首重 + 续重 * 续重费

        return $freight;
    }

    /**
     * 跟换地址获取邮费
     */
    public function getShippingFee(){
        //表单验证
        $vConf = array(
            array('product', '产品参数', 'required'),
            array('address_id', '地址id', 'required'),
        );
        $this->formDataValidation($vConf);

        $product = json_decode(post('product'),true);
        $address_id = post('address_id');

        //验证产品格式
        $tProduct = $this->mProduct->canAddOrder($this->userId, $product);
        if ( ! is_array($tProduct)){
            $this->appReturn(0,(is_string($tProduct) ? $tProduct : '格式错误'));
        }

        $_time = $this->mMerchant->getBusinessTimeList($tProduct[0]['merchant_id'],true);

        $this->loadModel('AdmSettingModel', 'mSet','admin');
        $_for = getCustomConfig('expect_take_time');
        $_other = $this->mSet->get('rob_expect_time', 'deliveryman');

        $tMaddress = $this->mMerchant->getShopInfo($tProduct[0]['merchant_id']);
        $week_str = explode(',', $tMaddress['business_week']);
        //送达时间
        $wxSD = appArriveTime($_time,$_for,$_other,$tMaddress['expect_arrive_time'],20,1,true);
        $selfWxSD = appArriveTime($_time,$_for,0,0,20, 1, true);

        $wxSDTime = $this->getWxSDTime($week_str,$wxSD);

        if(isset($wxSD['today']) && $wxSD['today']){
            $this->wxSDDefaultTime['time'] = isset($wxSD['today'][0]['value'])?$wxSD['today'][0]['value']:'';
        }else{
            $this->wxSDDefaultTime['time'] = isset($wxSD['other'][0]['value'])?$wxSD['other'][0]['value']:'';
        }
        $tData = $this->_orderFee($tProduct,$product,$address_id);
        $tData = array_values($tData);
        //立即送出时间
        $tData[0]['date'] = $wxSDTime[0]['value'];
        $tData[0]['time'] = $this->wxSDDefaultTime['time'];

        $this->appReturn(1,'',$tData);
    }

    /**
     * 根据所选地址，获取运费
     * @param array $productIds
     * @param number $addressId
     */
    private function shippingFee($product = array(),$address_id= 0, $done = false){

    	//加载模型
    	$this->loadModel('ConsumerAddressModel', 'mAddress','consumer');
//    	$this->loadModel('ConsumerProductModel', 'mProduct','consumer');
    	$this->loadModel('DlnOrderModel', 'mDln','deliveryman');
    	$this->loadModel('MerchantUserModel', 'mMerchant','merchant');
        $this->loadModel('AdmSettingModel', 'mSett', 'admin');

        //验证产品格式
    	$tProduct = $this->mProduct->canAddOrder($this->userId, $product);
    	if ( ! is_array($tProduct)){
    		$this->appReturn(0,(is_string($tProduct) ? $tProduct : '格式错误'));
    	}
    	
    	//获取用户地址所在地
    	$tAddress = $this->mAddress->getInfo($address_id,$this->userId);
    	if ( ! $tAddress){
    		$this->appReturn(0,'地址不存在');
    	}


    	//获取商家商品重量
    	$tWeight = array();
        $totalWeight = 0;//单商家
    	foreach ($tProduct as $k=>$v){
    		if ( ! isset($tWeight[$v['merchant_id']])){
    			$tWeight[$v['merchant_id']] = 0;
    		}
            if($v['v_weight'] > 0){
                $v['weight'] = $v['v_weight'];
            }
            $totalWeight += $v['weight'] * $v['b_quantity'];
    		$tWeight[$v['merchant_id']] += $v['weight'] * $v['b_quantity'];//单个重量 * 数量 获得总重量
    	}

        $tMid = array();
        foreach ($tProduct as $k=>$v){
            if ( ! in_array($v['merchant_id'],$tMid) ){
                $tMid[] = $v['merchant_id'];
            }
        }

        //获取商家
        $merchant_distance_limit = $this->mSett->get('merchant_distance_limit');

        $tMerchants = $this->mMerchant->getInfoByIds($tMid);
    	foreach ($tMerchants as $k=>$v){
    		if ( isset($tMerchants[$k]['distance']) ){
    		    //如果计算过距离则直接下个
                continue;
    		}

            //计算距离(米)
            $tMerchants[$k]['distance'] = getDistance($v['latitude'], $v['longitude'], $tAddress['latitude'], $tAddress['longitude']);
    		if($done && $tMerchants[$k]['distance'] > $merchant_distance_limit*1000){
                $this->appReturn(0,'不在商家配送范围内~');
            }
    	}

        $config = $this->mSett->get('base_distribution_fee,base_distribution_distance,exceed_base_distance,
                                    exceed_base_distance_number,base_distribution_weight,exceed_base_weight,
                                    exceed_base_weight_number','deliveryman');
    	//运费数据
    	$tData = array();
    	foreach ($tMerchants as $kk => $vv){
    	    $expect = (($vv['distance'] / 1000) - $config['base_distribution_distance']);//超出距离 km
            if($expect <= 0){
                $expect = 0;
            }
            $distance_amount = 0;
            if($config['exceed_base_distance_number'] > 0){
                $distance_amount = (ceil($expect / $config['exceed_base_distance_number']) * $config['exceed_base_distance']);
            }
            $expectW = $totalWeight - $config['base_distribution_weight'];
            if($expectW <= 0){
                $expectW = 0;
            }
            $weight_amount = 0;
            if($config['base_distribution_weight'] > 0 && $totalWeight > $config['base_distribution_weight']){
                $weight_amount += (ceil($expectW / $config['exceed_base_weight_number']) * $config['exceed_base_weight']);
            }

    	    $tData[$vv['id']] = array(
    				'merchant_id'=>(string)$vv['id'],
    				'shipping_fee'=>sprintf('%.2f',$this->mDln->getIncome($vv['distance']/1000, ceil($totalWeight))),
                    'base_amount'=>sprintf('%.2f',$config['base_distribution_fee']),//基础邮费
                    'distance'=>$vv['distance'],//距离
                    'weight'=>$totalWeight,//总重量
    	            'distance_amount'=>sprintf('%.2f',$distance_amount),//超出距离/费用
                    'weight_amount'=> sprintf('%.2f',$weight_amount),//超出重量/费用
                    'exceed_distance'=>sprintf('%.2f',$expect * 1000),//超出距离
                    'exceed_weight'=>sprintf('%.2f',$expectW),//超出重量
                    'is_free_shipping'=>1,
    		);
    	}

    	return $tData;
    }
    
}